package view;

import back.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

import static back.Head.*;

public class Register {
    private JPanel panel = new JPanel();
    private JTextField ip = new JTextField(16);
    private JPasswordField password = new JPasswordField(16);
    private JPasswordField repeatPassword = new JPasswordField(16);
    private JButton registerButton = new JButton("确认注册");

    public  Register() {

        panel.add(new JLabel("新用户注册",JLabel.CENTER));
        panel.add(new JLabel("新账号："));
        panel.add(ip);
        panel.add(new JLabel("新密码："));
        panel.add(password);
        panel.add(new JLabel("确认密码："));
        panel.add(repeatPassword);
        panel.add(registerButton);

        registerButton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                User user = mySQL_User.getUserByIP(ip.getText());
                if(user==null){
                    user = new User();
                    user.setId(ip.getText());
                    if(Arrays.equals(password.getPassword(), repeatPassword.getPassword())){
                        user.setPassword(new String(password.getPassword()));
                        if(mySQL_User.addUser(user)) {
                            container.removeAll();
                            container.add(login.GetPanel());
                            container.revalidate();
                            container.repaint();
                            frame.setVisible(true);
                        }
                    }else {
                        JOptionPane.showMessageDialog(panel, "两次输入密码不同！");
                    }
                }else{
                    JOptionPane.showMessageDialog(panel, "已有账户！");
                }
            }
        });

    }
    public JPanel GetPanel(){
        panel.setLayout(new GridLayout(10,1,0,15));
        return panel;
    }
}
